'''
ip pool;
'''
import requests
import json
from typing import List, Dict, Optional


class SimpleProxyPool:
    def __init__(self, url: str = None):
        """
        初始化代理池

        Args:
            url: 代理API的URL，如果提供则在初始化时自动获取代理
        """
        self.proxy_pool = []  # 存储代理IP列表
        self.current_index = 0  # 当前轮询索引

        # 如果提供了URL，则在初始化时自动获取代理
        if url:
            self.fetch_proxies(url)

    def fetch_proxies(self, url: str) -> bool:
        """
        从API获取代理IP并更新代理池

        Args:
            url: 完整的API URL

        Returns:
            bool: 是否成功获取并更新
        """
        try:
            # 清理URL中的换行符
            url = url.replace("\n", "").replace("\\n", "")

            print(f"正在获取代理IP: {url}")
            response = requests.get(url, timeout=30)

            if response.status_code != 200:
                print(f"请求失败，状态码: {response.status_code}")
                return False

            # 解析JSON响应
            json_data = json.loads(response.text)
            print(f"API返回: {json_data}")

            # 根据API实际返回格式提取IP列表
            new_proxies = []

            if "data" in json_data and isinstance(json_data["data"], list):
                new_proxies = json_data["data"]
            elif "result" in json_data and isinstance(json_data["result"], list):
                new_proxies = json_data["result"]
            elif isinstance(json_data, list):
                new_proxies = json_data
            else:
                new_proxies = [json_data] if isinstance(json_data, dict) else []

            # 更新代理池
            self.proxy_pool = new_proxies
            self.current_index = 0  # 重置索引

            print(f"成功更新IP池，共 {len(self.proxy_pool)} 个IP")
            return True

        except Exception as e:
            print(f"获取代理IP失败: {e}")
            return False

    def get_next_proxy(self) -> Optional[Dict]:
        """
        轮询获取下一个代理IP

        Returns:
            代理信息字典，如果没有代理则返回None
        """
        if not self.proxy_pool:
            return None

        # 轮询获取
        proxy = self.proxy_pool[self.current_index]
        self.current_index = (self.current_index + 1) % len(self.proxy_pool)

        return proxy

    def get_proxy_count(self) -> int:
        """获取当前代理池中的代理数量"""
        return len(self.proxy_pool)

    def clear_pool(self):
        """清空代理池"""
        self.proxy_pool = []
        self.current_index = 0
        print("代理池已清空")

    def get_all_proxies(self) -> List[Dict]:
        """获取所有代理（用于调试）"""
        return self.proxy_pool.copy()

    def is_empty(self) -> bool:
        """检查代理池是否为空"""
        return len(self.proxy_pool) == 0


if __name__ == "__main__":
    proxy_pool = SimpleProxyPool(url="http://api.shenlongproxy.com/ip?cty=JP&c=10&pt=1&ft=json&pat=\n&rep=1&key=fd86c71b&ts=6")
    print(proxy_pool.get_all_proxies())